package cn.Liujialin.basic.intercetor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component  //一定要交给容器管理
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        //1.从请求头获取token
        String token = request.getHeader("token");//e300994a-f0f7-4a17-820f-36f91a5dbea4
        //2.如果拿到了
        if(!StringUtils.isEmpty(token)){
            Object o = redisTemplate.opsForValue().get(token);//e300994a-f0f7-4a17-820f-36f91a5dbea4
            if(o != null){
                redisTemplate.opsForValue().set(token,o,30, TimeUnit.MINUTES);
                return true;// 放行
            }
        }
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        writer.flush();
        writer.close();
        return false;//阻值放行



        /*//2.如果获取不到，直接报错
        if(StringUtils.isEmpty(token)){
            response.setContentType("application/json;charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write("{\"success\":false,\"message\":\"noLogin\"}");
            writer.flush();
            writer.close();
            return false;//阻值放行
        }
        //3.根据token值，从redis拿登录信息
        Object o = redisTemplate.opsForValue().get(token);//e300994a-f0f7-4a17-820f-36f91a5dbea4
        //4.如果拿不到 报错
        if(o == null){
            response.setContentType("application/json;charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write("{\"success\":false,\"message\":\"noLogin\"}");
            writer.flush();
            writer.close();
            return false;//阻值放行
        }
        //5.都没有问题，放行
        redisTemplate.opsForValue().set(token,o,30, TimeUnit.MINUTES);
        return true;//放行*/
    }
}

